﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.ComponentModel;

namespace ICeFramework.Common.Utilities
{
    public class Reflection
    {
        public static object GetValue(object componentInstance, PropertyInfo propertyInfo, bool useDefaultIfAny, bool includeDefaultValue)
        {
            return GetValue(componentInstance, propertyInfo.Name, useDefaultIfAny, includeDefaultValue);
        }

        public static object GetValue(object componentInstance, string propertyName, bool useDefaultIfAny, bool includeDefaultValue)
        {
            object value = TypeDescriptor.GetProperties(componentInstance.GetType())[propertyName].GetValue(componentInstance);
            object defVal = null;
            AttributeCollection attributes =
                TypeDescriptor.GetProperties(componentInstance.GetType())[propertyName].Attributes;

            DefaultValueAttribute myAttribute =
               (DefaultValueAttribute)attributes[typeof(DefaultValueAttribute)];

            if (myAttribute != null)
            {
                defVal = myAttribute.Value;
            }

            if (!includeDefaultValue && value != null && value.Equals(defVal))
            {
                return null;
            }

            if (value == null && useDefaultIfAny && includeDefaultValue)
            {
                return defVal;
            }
            return value;
        }

        public static Attribute GetAttribute(object componentInstance, PropertyInfo propertyInfo, Type attributeType)
        {
            return GetAttribute(componentInstance, propertyInfo.Name, attributeType);
        }

        public static Attribute GetAttribute(object componentInstance, string propertyName, Type attributeType)
        {
            if (attributeType == null)
            {
                return null;
            }
            PropertyInfo propertyInfo = componentInstance.GetType().GetProperty(propertyName, BindingFlags.Public | BindingFlags.Instance);
            if (propertyInfo == null)
            {
                return null;
            }
            System.ComponentModel.AttributeCollection attributes =
                TypeDescriptor.GetProperties(propertyInfo.DeclaringType)[propertyInfo.Name].Attributes;

            return attributes[attributeType];
        }
    }
}
